import axios, { AxiosInstance, AxiosResponse } from 'axios'
import router from '@/router'
import {getAccessToken} from "@/utils/auth";
import {ElMessage} from "element-plus";

const Axios: AxiosInstance = axios.create({
    timeout: 5000,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    withCredentials: true
})

// 请求头拦截器
Axios.interceptors.request.use(config => {
    if(getAccessToken()) {
        config.headers.Authorization = getAccessToken()
    }
    return config
}, err => {
    Promise.reject(err);
})


// 响应拦截器
Axios.interceptors.response.use((res: AxiosResponse) => {
    return res
}, (err: any) => {
    // 失败时进入这里，内容根据store文件里的内容可替换
    if (err.response && err.response.status === 401) {
        // 清空无效用户信息
        // encodeURIComponent转换uri编码，防止解析地址出问题
        // router.currentRoute.value.fullPath就是当前路由地址
        const fullPath = encodeURIComponent(router.currentRoute.value.fullPath);
        // 跳转到登录页
        router.push('/login/redirectUrl=' + fullPath)
    }
    ElMessage.error(err.msg || '登录失败')
})

export default Axios
